import { Connection, ConnectionManager, getConnectionOptions, createConnection, getConnectionManager } from 'typeorm'
import { SnakeNamingStrategy } from 'typeorm-naming-strategies'
import 'reflect-metadata'
/**
* Database manager class
*/
export default class Database {
  private connectionManager: ConnectionManager
  constructor() {
    this.connectionManager = getConnectionManager()
  }
  public async getConnection(CONNECTION_NAME?: string): Promise<any> {
    CONNECTION_NAME = CONNECTION_NAME || `default`
    let connection: Connection
    if (this.connectionManager.has(CONNECTION_NAME)) {
      connection = await this.connectionManager.get(CONNECTION_NAME)
      if (!connection.isConnected) {
        connection = await connection.connect()
      }
    }
    else {
      const connectionOptions = await getConnectionOptions();
      Object.assign(connectionOptions, { namingStrategy: new SnakeNamingStrategy() });
      connection = await createConnection(connectionOptions)
    }
    return connection
  }
}
